﻿package com.farm.bpm.web.action;

import com.farm.bpm.server.FarmBpmServiceInter;

import com.farm.report.FarmReport;
import com.farm.web.easyui.EasyUiUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.repository.ProcessDefinition;
import com.farm.core.page.CommitType;
import com.farm.core.page.PageSet;
import com.farm.core.page.PageType;
import com.farm.core.sql.query.DataQuery;
import com.farm.doc.domain.FarmDocfile;
import com.farm.doc.server.FarmFileManagerInter;
import com.farm.doc.server.FarmFileManagerInter.FILE_TYPE;
import com.farm.web.WebSupport;
import com.farm.web.spring.BeanFactory;

/**
 * 部署流程类功能说明
 * 
 * @author 作者:自动生成
 * @version 日期(用日期代替版本号)+版本备注
 */
public class ActionActReProcdefQuery extends WebSupport {
	private Map<String, Object> jsonResult;// 结果集合
	private DataQuery query;// 条件查询
	private PageSet pageset;// 请求状态
	private String ids;// 主键集合
	private File xmlFile;
	private int error;
	private String url;
	private String message;
	private String id;
	private String xmlFileFileName;
	private InputStream inputStream;
	private String filename;
	private String xml;
	private String flowType;
	private String processDefId;
	private String titleDes;

	/**
	 * 查询当前部署流程
	 * 
	 * @return
	 */
	public String queryall() {
		try {
			query = EasyUiUtils.formatGridQuery(getRequest(), query);
			jsonResult = EasyUiUtils.formatGridData(aloneIMP
					.queryProcessDef(query));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return SUCCESS;
	}

	/**
	 * 查询启动者
	 * 
	 * @return
	 */
	public String queryStarter() {
		try {
			query = EasyUiUtils.formatGridQuery(getRequest(), query);
			jsonResult = EasyUiUtils.formatGridData(aloneIMP
					.queryProcessStartIdentityLinks(query, ids));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return SUCCESS;
	}

	/**
	 * 导入流程文件BPMN 2.0
	 * 
	 * @return
	 */
	public String addSubmit() {
		try {
			FarmDocfile file = fileIMP.getFile(id);
			aloneIMP.deployBpmn20XmlFile(file.getInputStream(), file.getName(),
					flowType);
			pageset = new PageSet(PageType.ADD, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.ADD,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	/**
	 * 修改流程定义
	 * 
	 * @return
	 */
	public String editSubmit() {
		try {
			aloneIMP.editProcessDefInfo(ids, flowType, titleDes);
			pageset = new PageSet(PageType.ADD, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.ADD,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	/**
	 * 删除流程定义
	 * 
	 * @return
	 */
	public String delSubmit() {
		try {
			for (String id : parseIds(ids)) {
				aloneIMP.deleteProcessDef(id);
			}
			pageset = new PageSet(PageType.ADD, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.DEL,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	/**
	 * 激活流程
	 * 
	 * @return
	 */
	public String startSubmit() {
		try {
			for (String id : parseIds(ids)) {
				aloneIMP.activateProcessDefinitionById(id);
			}
			pageset = new PageSet(PageType.ADD, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.DEL,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	/**
	 * 暂停流程
	 * 
	 * @return
	 */
	public String stopSubmit() {
		try {
			for (String id : parseIds(ids)) {
				aloneIMP.suspendProcessDefinitionById(id);
			}
			pageset = new PageSet(PageType.ADD, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.DEL,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	/**
	 * 导出文件
	 * 
	 * @return
	 */
	public String download() {
		try {
			inputStream = aloneIMP.getBpmn20XmlFile(ids);
			filename = aloneIMP.getBpmn20XmlFileName(ids);
			pageset = new PageSet(PageType.ADD, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.DEL,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	/**
	 * 获得工作流BPMN2.0xml文件编写指导
	 * 
	 */
	public String downIdReport() {
		try {
			Map<String, Object> report = aloneIMP.getBPMN20xmlUserGuideReport();
			filename = "BPMN_CODE.xls";
			inputStream = FarmReport.newInstance("IdCodeReport.xls")
					.addParameter("list", report.get("roles")).addParameter(
							"list2", report.get("users")).addParameter("list3",
							report.get("vars")).addParameter("list4",
							report.get("forms")).generate();
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.DEL,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	/**
	 * 导出文件
	 * 
	 * @return
	 */
	public String downImg() {
		try {
			inputStream = aloneIMP.getProcessDefDiagram(ids);
			if (inputStream == null) {
				return "error";
			}
			filename = "flowImg";
			pageset = new PageSet(PageType.ADD, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.DEL,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	/**
	 * 上传文件
	 * 
	 * @return
	 */
	public String upload() {
		try {
			String fileid = null;
			fileid = fileIMP.saveFile(xmlFile, FILE_TYPE.OHTER, xmlFileFileName,
					getCurrentUser());
			error = 0;
			url = fileIMP.getFileURL(fileid);
			message = "";
			id = fileid;
		} catch (Exception e) {
			error = 1;
			message = e.getMessage();
		}
		return SUCCESS;
	}

	@Override
	public void addActionError(String anErrorMessage) {
		// 这里要先判断一下，是我们要替换的错误，才处理
		if (anErrorMessage
				.startsWith("Request exceeded allowed size limit! Max size allowed is")) {
			Pattern pattern = Pattern.compile("[,|\\d]+");
			Matcher m = pattern.matcher(anErrorMessage);
			// 匹配一次
			m.find();
			String s1 = m.group().replaceAll(",", "");// 上传的文件大小
			// 再匹配一次
			m.find();
			String s2 = m.group().replaceAll(",", "");// 所限制的大小
			String fileUploadErrorMessage = null;
			if (!s1.equals("") && !s2.equals("")) {
				fileUploadErrorMessage = "你上传的文件大小（" + Long.valueOf(s2) / 1024
						/ 1024 + "M）超过允许的大小（" + Long.valueOf(s1) / 1024 / 1024
						+ "M）";
				getRequest().setAttribute("fileUploadErrorMessage",
						fileUploadErrorMessage);
				// 将信息替换掉
				super.addActionError(fileUploadErrorMessage);
			}
		} else {// 否则按原来的方法处理
			super.addActionError(anErrorMessage);
		}
	}

	public String addStartUserSubmit() {
		try {
			aloneIMP.addProcessStartUser(processDefId, id);

			pageset = new PageSet(PageType.ADD, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.DEL,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	public String addStartRuleSubmit() {
		try {
			aloneIMP.addProcessStartRole(processDefId, id);

			pageset = new PageSet(PageType.ADD, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.DEL,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	public String delStartSubmit() {
		try {
			for (String id : parseIds(ids)) {
				aloneIMP.delStartUserOrRole(processDefId, id);
			}
			pageset = new PageSet(PageType.ADD, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.DEL,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	/**
	 * 跳转
	 * 
	 * @return
	 * @throws Exception
	 */
	public String forSend() {
		if(pageset.getPageType()==PageType.UPDATE.value){
			ProcessDefinition pi = aloneIMP.getProcessDefinition(ids);
			if(pi!=null){
				titleDes = pi.getDescription();
				flowType = pi.getCategory();
			}
		}
		return SUCCESS;
	}

	/**
	 * 显示详细信息（修改或浏览时）
	 * 
	 * @return
	 */
	public String view() {
		try {
			inputStream = processEngine.getRepositoryService().getProcessModel(
					ids);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int i = -1;
			while ((i = inputStream.read()) != -1) {
				baos.write(i);
			}
			xml = baos.toString("utf8");
			pageset = new PageSet(PageType.SHOW, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.OTHER,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	private final static FarmBpmServiceInter aloneIMP = (FarmBpmServiceInter) BeanFactory
			.getBean("farmBpmProxyId");
	private final static ProcessEngine processEngine = (ProcessEngine) BeanFactory
			.getBean("processEngine");
	private final static FarmFileManagerInter fileIMP = (FarmFileManagerInter) BeanFactory
	.getBean("farm_docFileProxyId");
	// ----------------------------------------------------------------------------------
	public DataQuery getQuery() {
		return query;
	}

	public void setQuery(DataQuery query) {
		this.query = query;
	}

	public PageSet getPageset() {
		return pageset;
	}

	public void setPageset(PageSet pageset) {
		this.pageset = pageset;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public Map<String, Object> getJsonResult() {
		return jsonResult;
	}

	public void setJsonResult(Map<String, Object> jsonResult) {
		this.jsonResult = jsonResult;
	}

	public File getXmlFile() {
		return xmlFile;
	}

	public void setXmlFile(File xmlFile) {
		this.xmlFile = xmlFile;
	}

	public int getError() {
		return error;
	}

	public void setError(int error) {
		this.error = error;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getXmlFileFileName() {
		return xmlFileFileName;
	}

	public void setXmlFileFileName(String xmlFileFileName) {
		this.xmlFileFileName = xmlFileFileName;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public String getXml() {
		return xml;
	}

	public void setXml(String xml) {
		this.xml = xml;
	}

	public String getFlowType() {
		return flowType;
	}

	public void setFlowType(String flowType) {
		this.flowType = flowType;
	}

	public String getProcessDefId() {
		return processDefId;
	}

	public void setProcessDefId(String processDefId) {
		this.processDefId = processDefId;
	}

	public String getTitleDes() {
		return titleDes;
	}

	public void setTitleDes(String titleDes) {
		this.titleDes = titleDes;
	}

//	private static final Logger log = Logger
//			.getLogger(ActionActReProcdefQuery.class);
	private static final long serialVersionUID = 1L;
	/**
	 * 加载树节点 public String loadTreeNode() { treeNodes =
	 * EasyUiTreeNode.formatAjaxTree(EasyUiTreeNode .queryTreeNodeOne(id,
	 * "SORT", "alone_menu", "ID", "PARENTID", "NAME").getResultList(),
	 * EasyUiTreeNode .queryTreeNodeTow(id, "SORT", "alone_menu", "ID",
	 * "PARENTID", "NAME").getResultList(), "PARENTID", "ID", "NAME"); return
	 * SUCCESS; }
	 * 
	 * @return
	 */
}
